package com.echoesnet.echoesshortvideo.ViewModels;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;

import com.echoesnet.echoesshortvideo.Api.Subscriber.SilenceSubscriber;
import com.echoesnet.echoesshortvideo.Persistence.TinyVideoInfoEntity;
import com.echoesnet.echoesshortvideo.Repositories.TinyVideoInfoRepository;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C) 2018 科技发展有限公司
 * 完全享有此软件的著作权，违者必究
 * 负责驱动UI
 *
 * @author ben
 * @version 1.0
 * @modifier
 * @createDate 2018/4/19 18:05
 * @description
 */
public class ListOfVideoClipsViewModel extends ViewModel
{
    private MutableLiveData<Integer> increases = new MutableLiveData<>();
    private MutableLiveData<Boolean> loadmore = new MutableLiveData<>();
    private MutableLiveData<Map<String, String>> checkVideoResult = new MutableLiveData<>();
    private LiveData<List<TinyVideoInfoEntity>> list;
    private TinyVideoInfoRepository tinyVideoInfoRepository;

    private int iStart = 0;
    private final int iStep = 10;

    public ListOfVideoClipsViewModel()
    {
        this.tinyVideoInfoRepository = new TinyVideoInfoRepository();
    }

    public LiveData<List<TinyVideoInfoEntity>> list()
    {
        list = tinyVideoInfoRepository.getListByUpdate();
        return list;
    }

    public MutableLiveData<Boolean> loadmore()
    {
        return loadmore;
    }

    public MutableLiveData<Map<String, String>> getCheckVideoResult()
    {
        return checkVideoResult;
    }

    public MutableLiveData<Integer> getIncreases()
    {
        return increases;
    }

    public void requestRefresh()
    {
        iStart = 0;
        tinyVideoInfoRepository.getHomePageVideoList(iStart, iStep);
        loadmore.setValue(true);
    }

    public void requestMore()
    {
        iStart += iStep;
        tinyVideoInfoRepository.getHomePageVideoList(iStart, iStep, loadmore);
    }

    public void checkVideoState(String videoId, String openSource)
    {
        tinyVideoInfoRepository.checkVideo(videoId, new SilenceSubscriber<String>()
        {
            @Override
            public void onNext(String response)
            {
                super.onNext(response);
                try
                {
                    JSONObject object = new JSONObject(response);
                    String result = object.getString("delStatus");
                    Map<String, String> map = new HashMap();
                    map.put("videoId", videoId);
                    map.put("openSource", openSource);
                    map.put("result", result);
                    checkVideoResult.setValue(map);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

}
